<template>
  <div>
    <Breadcrumb menu="商品管理" submenu="分类参数" />
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数!"
        :closable="false"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <div class="cat_ops">
        <span>选择商品分类:</span>
        <el-cascader
          @change="handleChange"
          v-model="selectKeys"
          clearable
          :options="allCateList"
          :props="cascaderProps"
        ></el-cascader>
      </div>
      <!-- tab页面区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板-->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            @click="addParamsDialogVisible = true"
            type="primary"
            size="mini"
            :disabled="isBtnEnabled"
            >添加参数</el-button
          >
          <!-- 动态参数列表 -->
          <el-table border stripe :data="manyTabData" style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(it, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteAttrVals(i, row)"
                  >{{ it }}</el-tag
                >
                <el-input
                  class="input_new_tag"
                  v-if="row._eidt_attr"
                  v-model.trim="row._attr_vals"
                  ref="editAttrValsRef"
                  size="small"
                  @keyup.enter.native="saveEditAttrVals(row)"
                  @blur="cancelEditAttrVals(row)"
                >
                </el-input>
                <el-button
                  class="btn_new_tag"
                  v-else
                  size="small"
                  @click="editAttrVals(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="attr_id" label="id" width="100px">
            </el-table-column>
            <el-table-column label="参数名称">
              <template v-slot="{ row }">
                <span v-if="!row._edit">{{ row.attr_name }}</span>
                <el-input
                  @keyup.enter.native="saveEditInfo(row)"
                  @blur="editBtnCancel(row)"
                  ref="editAttrNameRef"
                  v-else
                  v-model="row._attr_name"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <!-- 编辑按钮 -->
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  round
                  @click="editAttrName(row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  @click="deleteParamsById(row)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  round
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            @click="addParamsDialogVisible = true"
            type="primary"
            size="mini"
            :disabled="isBtnEnabled"
            >添加属性</el-button
          >
          <!-- 静态属性列表 -->
          <el-table border stripe :data="onlyTabData" style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(it, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteAttrVals(i, row)"
                  >{{ it }}</el-tag
                >
                <el-input
                  class="input_new_tag"
                  v-if="row._eidt_attr"
                  v-model.trim="row._attr_vals"
                  ref="editAttrValsRef"
                  size="small"
                  @keyup.enter.native="saveEditAttrVals(row)"
                  @blur="cancelEditAttrVals(row)"
                >
                </el-input>
                <el-button
                  class="btn_new_tag"
                  v-else
                  size="small"
                  @click="editAttrVals(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="attr_id" label="id" width="100px">
            </el-table-column>
            <el-table-column label="属性名称">
              <template v-slot="{ row }">
                <span v-if="!row._edit">{{ row.attr_name }}</span>
                <el-input
                  v-else
                  ref="editAttrNameRef"
                  v-model="row._attr_name"
                  @keyup.enter.native="saveEditInfo(row)"
                  @blur="editBtnCancel(row)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <!-- 编辑按钮 -->
                <el-button
                  @click="editAttrName(row)"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  round
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  @click="deleteParamsById(row)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  round
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + addParamsDialogTitle"
      :visible.sync="addParamsDialogVisible"
      width="30%"
      @close="addParamsDialogClose"
    >
      <el-form
        ref="addParamsFormRef"
        :rules="addParamsFormRules"
        :model="addParamsForm"
        label-width="80px"
      >
        <el-form-item :label="addParamsDialogTitle" prop="attrName">
          <el-input v-model="addParamsForm.attrName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      //所有的商品分类列表数据
      allCateList: [],
      selectKeys: [],
      // 指定级联选择的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      activeName: "many",
      //动态参数列表数据
      manyTabData: [],
      //静态属性列表数据
      onlyTabData: [],
      //控制添加参数对话框的显示和隐藏
      addParamsDialogVisible: false,
      //添加参数表单数据
      addParamsForm: {
        attrName: "",
      },
      //添加参数校验规则
      addParamsFormRules: {
        attrName: [
          {
            required: true,
            message: `请输入参数名称`,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //获取所有的商品分类列表
    async getAllCateList() {
      const { data: res } = await this.$http.get("categories");
      this.allCateList = res.data;
    },
    handleChange() {
      this.getParamsData();
    },
    //获取参数数据
    async getParamsData() {
      if (this.selectKeys.length < 3) {
        this.selectKeys = [];
        this.onlyTabData = [];
        this.manyTabData = [];
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      res.data.forEach((el) => {
        el._attr_name = el.attr_name;
        el._edit = false;
        el._eidt_attr = false;
        el.attr_vals = el.attr_vals ? el.attr_vals.split(" ") : [];
        el._attr_vals;
      });
      if (this.activeName === "only") {
        this.onlyTabData = res.data;
      } else {
        this.manyTabData = res.data;
      }
    },
    handleTabClick() {
      this.getParamsData();
    },
    addParamsDialogClose() {
      this.$refs.addParamsFormRef.resetFields();
    },
    addParams() {
      this.$refs.addParamsFormRef.validate(async (val) => {
        if (!val) return;
        const { data: res } = await this.$http.post(
          `categories/${this.catId}/attributes`,
          {
            attr_name: this.addParamsForm.attrName,
            attr_sel: this.activeName,
          }
        );
        res.data._attr_name = res.data.attr_name;
        res.data._edit = false;
        if (this.activeName === "only") {
          this.onlyTabData.push(res.data);
        } else {
          this.manyTabData.push(res.data);
        }
        this.$message.success(
          `添加${this.addParamsDialogTitle} ${this.addParamsForm.attrName} 成功`
        );
        this.addParamsDialogVisible = false;
      });
    },
    editBtnCancel(row) {
      row._edit = false;
      row._attr_name = row.attr_name;
    },
    async saveEditInfo(row) {
      await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row._attr_name,
          attr_sel: this.activeName,
        },
        {
          rejectCall: () => {
            row._edit = false;
          },
        }
      );
      row.attr_name = row._attr_name;
      row._edit = false;
      this.$message.success(`修改${this.paramsName}成功`);
    },
    deleteParamsById(row) {
      this.$confirm(
        `此操作将永久删除${this.paramsName} ${row.attr_name}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          await this.$http.delete(
            `categories/${row.cat_id}/attributes/${row.attr_id}`
          );
          this.$message.success(`删除${this.paramsName} ${row.attr_name} 成功`);
          if (this.activeName === "only") {
            this.onlyTabData.remove(row);
          } else {
            this.manyTabData.remove(row);
          }
        })
        .catch((error) => error);
    },
    editAttrName(row) {
      row._edit = true;
      this.$nextTick((_) => {
        this.$refs.editAttrNameRef.focus();
      });
    },
    editAttrVals(row) {
      row._eidt_attr = true;
      this.$nextTick((_) => {
        this.$refs.editAttrValsRef.focus();
      });
    },
    cancelEditAttrVals(row) {
      row._eidt_attr = false;
      row._attr_vals = "";
    },
    async saveEditAttrVals(row) {
      row._eidt_attr = false;
      if (!row._attr_vals) return;
      row.attr_vals.push(row._attr_vals);
      row._attr_vals = "";
      await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      this.$message.success("添加成功");
    },
    async deleteAttrVals(i, row) {
      row.attr_vals.delete(i);
      await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      this.$message.success("删除成功");
    },
  },
  computed: {
    paramsName() {
      return this.activeName === "only" ? "属性名称" : "参数名称";
    },
    catId() {
      return this.selectKeys.last();
    },
    isBtnEnabled() {
      return this.selectKeys.length !== 3;
    },
    addParamsDialogTitle() {
      return this.activeName === "only" ? "静态属性" : "动态参数";
    },
  },
  created() {
    this.getAllCateList();
    this.getParamsData();
  },
};
</script>

<style lang="less" scoped>
.cat_ops {
  margin: 15px 0;
  .el-cascader {
    margin-left: 10px;
    width: 25%;
  }
}

.el-table .el-input /deep/ input {
  height: 25px;
  width: 50%;
}

.el-tag {
  margin-left: 15px;
  margin-bottom: 15px;
}
.btn_new_tag {
  margin-left: 15px;
}
.input_new_tag {
  width: 150px;
  margin-left: 15px;
}
</style>